<template>
  <div>
    <!-- 查询栏 -->
    <el-form :inline="true" :model="storePurchaseDTO" class="demo-form-inline">
      <el-form-item label="采购单号">
        <el-input v-model="storePurchaseDTO.purchaseNo" placeholder="采购单号" @keyup.enter.native="onSearch"></el-input>
      </el-form-item>
      <el-form-item label="订单号">
        <el-input v-model="storePurchaseDTO.orderNo" placeholder="订单号" @keyup.enter.native="onSearch"></el-input>
      </el-form-item>
      <el-form-item label="物流公司">
        <el-input v-model="storePurchaseDTO.logisticsCompany" placeholder="物流公司" @keyup.enter.native="onSearch"></el-input>
      </el-form-item>
      <el-form-item label="物流单号">
        <el-input v-model="storePurchaseDTO.trackingNo" placeholder="物流单号" @keyup.enter.native="onSearch"></el-input>
      </el-form-item>
      <el-form-item label="仓库名称">
        <el-input v-model="storePurchaseDTO.warehouse" placeholder="仓库名称" @keyup.enter.native="onSearch"></el-input>
      </el-form-item>
      <el-form-item label="状态">
        <el-select v-model="storePurchaseDTO.status" placeholder="状态" clearable>
          <el-option label="待分拣" value="待分拣"></el-option>
          <el-option label="待入库" value="待入库"></el-option>
          <el-option label="部分入库" value="部分入库"></el-option>
          <el-option label="完全入库" value="完全入库"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="数量">
        <el-input v-model="storePurchaseDTO.quantity" placeholder="数量" @keyup.enter.native="onSearch" type="number"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="onSearch">查询</el-button>
        <el-button type="warning" @click="onReset">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 按钮 -->
    <el-button size="small" type="primary" @click="handleAdd" style="margin-left: 10px">新增</el-button>
    <el-button size="small" type="danger" @click="handleBatchDelete">删除</el-button>
    <el-button size="small" type="info" @click="handleImport">导入</el-button>
    <el-button size="small" type="warning" @click="handleExport">导出</el-button>
    <input type="file" ref="fileInput" @change="triggerImport" style="display: none;" accept=".xlsx, .xls" />

    <!-- 表格 -->
    <el-table :data="tableData" style="width: 100%" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55"></el-table-column>
      <el-table-column label="采购图片">
        <template slot-scope="scope">
          <image-preview :src="scope.row.image" />
        </template>
      </el-table-column>
      <el-table-column prop="purchaseNo" label="采购单号"></el-table-column>
      <el-table-column prop="orderNo" label="订单号"></el-table-column>
      <el-table-column prop="logisticsCompany" label="物流公司"></el-table-column>
      <el-table-column prop="trackingNo" label="物流单号"></el-table-column>
      <el-table-column prop="warehouse" label="仓库名称"></el-table-column>
      <el-table-column prop="quantity" label="数量"></el-table-column>
      <el-table-column prop="status" label="状态">
        <template slot-scope="scope">
          <el-tag :type="{
            '待分拣': 'info',
            '待入库': 'warning',
            '部分入库': 'primary',
            '完全入库': 'success'
          }[scope.row.status]">
            {{ scope.row.status }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="createTime" label="创建时间"></el-table-column>
      <el-table-column prop="storageTime" label="入库时间"></el-table-column>
      <el-table-column prop="receivingTime" label="收货时间"></el-table-column>
      <el-table-column label="操作">
        <template slot-scope="scope">
          <el-button size="mini" type="primary" @click="handleEdit(scope.$index, scope.row)">修改</el-button>
          <el-button size="mini" type="danger" @click="handleDelete(scope.$index, scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <el-pagination
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="storePurchaseDTO.pageNum"
      :page-sizes="[5,10,20]"
      :page-size="storePurchaseDTO.pageSize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total">
    </el-pagination>

    <!-- 新增/修改弹窗 -->
    <el-dialog :title="dialogTitle" :visible.sync="dialogVisible" width="30%" @closed="resetForm('purchaseForm')">
      <el-form :model="form" :rules="rules" ref="purchaseForm">
        <el-form-item label="采购图片" label-width="100px" prop="image">
          <image-upload v-model="form.image" />
        </el-form-item>
        <el-form-item label="采购单号" label-width="100px" prop="purchaseNo">
          <el-input v-model="form.purchaseNo" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="订单号" label-width="100px" prop="orderNo">
          <el-input v-model="form.orderNo" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="物流公司" label-width="100px" prop="logisticsCompany">
          <el-input v-model="form.logisticsCompany" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="物流单号" label-width="100px" prop="trackingNo">
          <el-input v-model="form.trackingNo" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="仓库名称" label-width="100px" prop="warehouse">
          <el-select v-model="form.warehouse" placeholder="请选择仓库" style="width: 100%">
            <el-option
              v-for="item in warehouseOptions"
              :key="item.warehouseId"
              :label="item.warehouseName"
              :value="item.warehouseName">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="数量" label-width="100px" prop="quantity">
          <el-input-number v-model="form.quantity" :min="1" style="width: 100%"></el-input-number>
        </el-form-item>
        <el-form-item v-if="dialogTitle === '修改采购单'" label="状态" label-width="100px" prop="status">
          <el-select v-model="form.status" placeholder="状态" style="width: 100%">
            <el-option
              v-for="option in statusOptions"
              :key="option"
              :label="option"
              :value="option">
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="confirmDialog">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import ImagePreview from '@/components/ImagePreview/index.vue'
import ImageUpload from '@/components/ImageUpload/index.vue'
import { find, add, update, deletePurchases,importBatch } from '@/api/store/purchase';
import { find as findWarehouses } from '@/api/base/warehouse';

export default {
  name: 'StorePurchase',
  components: { ImagePreview, ImageUpload },
  data() {
    return {
      storePurchaseDTO: {
        purchaseNo: '',
        orderNo: '',
        logisticsCompany: '',
        trackingNo: '',
        warehouse: '',
        status: '',
        quantity: '',
        pageNum: 1,
        pageSize: 5
      },
      tableData: [],
      multipleSelection: [],
      total: 0,
      dialogVisible: false,
      dialogTitle: '',
      form: {
        id: '',
        image: '',
        purchaseNo: '',
        orderNo: '',
        logisticsCompany: '',
        trackingNo: '',
        warehouse: '',
        warehouseId: '',
        quantity: '',
        status: ''
      },
      rules: {
        image: [
          { required: true, message: '请上传采购图片', trigger: 'change' }
        ],
        purchaseNo: [
          { required: true, message: '请输入采购单号', trigger: 'blur' }
        ],
        orderNo: [
          { required: true, message: '请输入订单号', trigger: 'blur' }
        ],
        logisticsCompany: [
          { required: true, message: '请输入物流公司', trigger: 'blur' }
        ],
        trackingNo: [
          { required: true, message: '请输入物流单号', trigger: 'blur' }
        ],
        warehouse: [
          { required: true, message: '请选择仓库', trigger: 'change' }
        ],
        quantity: [
          { required: true, message: '请输入数量', trigger: 'blur' },
          { type: 'number', min: 1, message: '数量必须大于等于1', trigger: 'blur' }
        ],
        status: [
          { required: true, message: '请选择状态', trigger: 'change' }
        ]
      },
      warehouseOptions: [], // 所有仓库选项
      statusOptions: [] // 状态选项
    };
  },
  created() {
    this.fetchData();
    this.loadWarehouses(); // 加载所有仓库
  },
  methods: {
    // 加载所有仓库
    loadWarehouses() {
      const params = {
        pageNum: 1,
        pageSize: 1000
      };
      findWarehouses(params).then(res => {
        this.warehouseOptions = res.data.list || [];
      });
    },

    // 查询采购信息
    fetchData() {
      find(this.storePurchaseDTO).then(res => {
        this.tableData = res.data.list;
        this.total = res.data.total;
        this.$message({
          message: '查询成功!',
          type: 'success',
          duration: 1200
        });
      });
    },

    // 触发导入文件选择
    handleImport() {
      this.$refs.fileInput.click();
    },
    // 处理文件选择并上传
    triggerImport(e) {
      const file = e.target.files[0];
      if (file) {
        this.importData(file);
      }
    },
    // 执行导入请求
    importData(file) {
      importBatch(file).then(() => {
        this.$message({
          message: '导入成功!',
          type: 'success',
          duration: 1200
        });
        this.fetchData(); // 刷新数据
      });
    },
    // 导出
    handleExport() {
      window.location.href = 'http://localhost:8888/store/purchase/export';
    },

    // 重置表单
    resetForm(formName) {
      this.dialogVisible = false;
      this.$refs[formName].resetFields();
      this.form = {
        id: '',
        image: '',
        purchaseNo: '',
        orderNo: '',
        logisticsCompany: '',
        trackingNo: '',
        warehouse: '',
        warehouseId: '',
        quantity: '',
        status: ''
      };
      this.statusOptions = []; // 重置状态选项
    },

    // 条件查询
    onSearch() {
      this.storePurchaseDTO.pageNum = 1;
      this.fetchData();
    },

    // 重置查询条件
    onReset() {
      this.storePurchaseDTO.purchaseNo = '';
      this.storePurchaseDTO.orderNo = '';
      this.storePurchaseDTO.logisticsCompany = '';
      this.storePurchaseDTO.trackingNo = '';
      this.storePurchaseDTO.warehouse = '';
      this.storePurchaseDTO.status = '';
      this.storePurchaseDTO.quantity = '';
      this.fetchData();
    },

    // 多选
    handleSelectionChange(val) {
      this.multipleSelection = val;
    },

    // 修改按钮
    handleEdit(index, row) {
      this.dialogTitle = '修改采购单';

      // 获取对应仓库的ID
      const selectedWarehouse = this.warehouseOptions.find(item => item.warehouseName === row.warehouse);

      this.form = {
        id: row.id,
        image: row.image,
        purchaseNo: row.purchaseNo,
        orderNo: row.orderNo,
        logisticsCompany: row.logisticsCompany,
        trackingNo: row.trackingNo,
        warehouse: row.warehouse,
        warehouseId: selectedWarehouse ? selectedWarehouse.warehouseId : '',
        quantity: row.quantity,
        status: row.status
      };

      // 根据当前状态设置可选项
      this.updateStatusOptions(row.status);

      this.dialogVisible = true;
    },

    // 更新状态选项
    updateStatusOptions(currentStatus) {
      switch (currentStatus) {
        case '待分拣':
          this.statusOptions = ['待分拣', '待入库'];
          break;
        case '待入库':
          this.statusOptions = ['待入库', '部分入库'];
          break;
        case '部分入库':
          this.statusOptions = ['部分入库', '完全入库'];
          break;
        case '完全入库':
          this.statusOptions = ['完全入库'];
          break;
        default:
          this.statusOptions = [];
      }
    },

    // 新增按钮
    handleAdd() {
      this.dialogTitle = '新增采购单';
      this.form = {
        purchaseNo: '',
        orderNo: '',
        logisticsCompany: '',
        trackingNo: '',
        warehouse: '',
        warehouseId: '',
        quantity: '',
        status: ''
      };
      this.statusOptions = []; // 新增时不需要状态选项
      this.dialogVisible = true;
    },

    // 单选删除
    handleDelete(index, row) {
      const purchaseNo = row.purchaseNo;
      this.$confirm(`确定要删除采购单 "${purchaseNo}" 吗？`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        deletePurchases(row.id).then(response => {
          this.$message({
            message: '删除成功!',
            type: 'success',
            duration: 1200
          });
          this.fetchData();
        });
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    },

    // 批量删除
    handleBatchDelete() {
      if (this.multipleSelection.length === 0) {
        this.$message({
          message: '请选择要删除的数据!',
          type: 'warning',
          duration: 1200
        });
        return;
      } else {
        const purchaseNos = this.multipleSelection.map(item => item.purchaseNo).join(', ');
        this.$confirm(`确定要删除以下采购单吗？\n${purchaseNos}`, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          const ids = this.multipleSelection.map(item => item.id).join(',');
          deletePurchases(ids).then(response => {
            this.$message({
              message: '删除成功!',
              type: 'success',
              duration: 1200
            });
            this.fetchData();
          });
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          });
        });
      }
    },

    // 提交新增/修改
    confirmDialog() {
      this.$refs.purchaseForm.validate(valid => {
        if (valid) {
          // 获取对应的warehouseId
          const selectedWarehouse = this.warehouseOptions.find(item => item.warehouseName === this.form.warehouse);
          if (selectedWarehouse) {
            this.form.warehouseId = selectedWarehouse.warehouseId;
          }

          if (this.dialogTitle === '新增采购单') {
            add(this.form).then(response => {
              this.$message({
                message: '新增成功!',
                type: 'success',
                duration: 1200
              });
              this.fetchData();
              this.dialogVisible = false;
            });
          } else {
            update(this.form).then(response => {
              this.$message({
                message: '修改成功!',
                type: 'success',
                duration: 1200
              });
              this.fetchData();
              this.dialogVisible = false;
            });
          }
        } else {
          this.$message({
            message: '表单验证失败!',
            type: 'error',
            duration: 1200
          });
          return false;
        }
      });
    },

    // 改变每页大小
    handleSizeChange(val) {
      this.storePurchaseDTO.pageSize = val;
      this.fetchData();
    },

    // 改变当前页码
    handleCurrentChange(val) {
      this.storePurchaseDTO.pageNum = val;
      this.fetchData();
    }
  }
};
</script>

<style scoped lang="scss">
.demo-form-inline {
  margin-left: 10px;
  margin-top: 5px;
}
.el-pagination {
  margin: 5px;
  text-align: center;
}
</style>
